package com.example.tliaswebmanagement.exception;

import com.example.tliaswebmanagement.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice    // = @ControllerAdvice + @ResponseBody
public class GlobalException {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("程序出错了", e);
        return Result.error("出错了，请联系管理员修复");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("出现了DuplicateKey异常", e);
        String error = e.getMessage();
        int i = error.indexOf("Duplicate entry");
        String errMsg = error.substring(i);
        String[] s = errMsg.split(" ");

        return Result.error(s[2] + "已被占用");
    }
}
